import pyautogui
import time
import random
import argparse
import logging
from pynput import keyboard

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
logger = logging.getLogger(__name__)

class AntiLockScreen:
    def __init__(self, interval=30, move_distance=5, use_keyboard=True):
        """
        初始化防锁屏工具
        
        参数:
            interval: 操作间隔（秒）
            move_distance: 鼠标移动距离（像素）
            use_keyboard: 是否使用键盘模拟
        """
        self.interval = interval
        self.move_distance = move_distance
        self.use_keyboard = use_keyboard
        self.running = False
        self.listener = None
        
        # 注册退出热键（Ctrl+Alt+X）
        self.hotkey = keyboard.HotKey(
            keyboard.HotKey.parse('<ctrl>+<alt>+x'),
            self.stop
        )
        
    def on_press(self, key):
        """键盘按下事件处理"""
        try:
            self.hotkey.press(self.canonical(key))
        except AttributeError:
            pass
    
    def on_release(self, key):
        """键盘释放事件处理"""
        try:
            self.hotkey.release(self.canonical(key))
        except AttributeError:
            pass
    
    def canonical(self, key):
        """规范化键盘按键"""
        if hasattr(self.listener, 'canonical'):
            return self.listener.canonical(key)
        return key
    
    def simulate_mouse_move(self):
        """模拟鼠标微小移动（避开屏幕角落）"""
        current_x, current_y = pyautogui.position()
        
        # 确保不会移动到屏幕边缘
        screen_width, screen_height = pyautogui.size()
        safe_margin = 10  # 距离屏幕边缘的安全距离
        
        # 计算新位置（微小移动）
        new_x = current_x + random.randint(-self.move_distance, self.move_distance)
        new_y = current_y + random.randint(-self.move_distance, self.move_distance)
        
        # 确保不会超出安全区域
        new_x = max(safe_margin, min(new_x, screen_width - safe_margin))
        new_y = max(safe_margin, min(new_y, screen_height - safe_margin))
        
        # 移动鼠标
        pyautogui.moveTo(new_x, new_y, duration=0.1)
        logger.info(f"鼠标移动到: ({new_x}, {new_y})")
    
    def simulate_key_press(self):
        """模拟键盘按键（F15，通常无实际功能）"""
        pyautogui.press('f15')
        logger.info("模拟按下F15键")
    
    def trigger_activity(self):
        """触发系统活动"""
        if self.use_keyboard:
            self.simulate_key_press()
        else:
            self.simulate_mouse_move()
    
    def start(self):
        """启动防锁屏工具"""
        self.running = True
        logger.info(f"防锁屏工具已启动，间隔: {self.interval}秒")
        logger.info("按 Ctrl+Alt+X 停止工具")
        
        # 启动键盘监听
        self.listener = keyboard.Listener(
            on_press=self.on_press,
            on_release=self.on_release
        )
        self.listener.start()
        
        try:
            while self.running:
                self.trigger_activity()
                time.sleep(self.interval)
        except KeyboardInterrupt:
            logger.info("用户中断，停止工具")
        finally:
            self.stop()
    
    def stop(self):
        """停止防锁屏工具"""
        self.running = False
        if self.listener:
            self.listener.stop()
        logger.info("防锁屏工具已停止")

def main():
    parser = argparse.ArgumentParser(description="Windows防锁屏工具")
    parser.add_argument("-i", "--interval", type=int, default=30, 
                        help="操作间隔（秒），默认30秒")
    parser.add_argument("-d", "--distance", type=int, default=5, 
                        help="鼠标移动距离（像素），默认5像素")
    parser.add_argument("--no-keyboard", action="store_true", 
                        help="仅使用鼠标模拟，不使用键盘")
    
    args = parser.parse_args()
    
    anti_lock = AntiLockScreen(
        interval=args.interval,
        move_distance=args.distance,
        use_keyboard=not args.no_keyboard
    )
    anti_lock.start()

if __name__ == "__main__":
    main()
    # python anti_lock_screen.py -i 30 -d 5 --no-keyboard